package com.mxdx.edu.conf;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.velocity.VelocityViewResolver;

import com.mxdx.edu.interceptor.AuthInterceptor;
import com.mxdx.edu.util.DefineVelocityToolboxView;

/**
 * 静态资源配置
 * 
 * @author guoxc
 * 
 */
@Configuration
public class WebAppConfigurer extends WebMvcConfigurerAdapter {

    @Value("${spring.velocity.view.suffix}")
    private String viewSuffix;

    @Value("${spring.velocity.view.isCache}")
    private String isViewCache;

    @Resource
    private AuthInterceptor authInterceptor;

    /**
     * 自定义reslover， 用于加载自定义的velocity toolbox
     * 
     * @return
     */
    @Bean
    public ViewResolver viewResolver() {
        VelocityViewResolver resolver = new VelocityViewResolver();
        resolver.setViewClass(DefineVelocityToolboxView.class);
        resolver.setSuffix(viewSuffix);
        resolver.setContentType("text/html;charset=utf-8");
        resolver.setExposeRequestAttributes(true);
        resolver.setRequestContextAttribute("rc");
        resolver.setCache(Boolean.parseBoolean(isViewCache));
        return resolver;
    }


    /**
     * 加入自定义的404页面
     * 
     * @return
     */
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {

        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/v/404");
                container.addErrorPages(error404Page);
            }


        };
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor).addPathPatterns("/**/auth/**");
        registry.addInterceptor(authInterceptor).addPathPatterns("/**/public/jxjyIndex");
    }

}
